from waveapi import events
from waveapi import model
from waveapi import robot
from google.appengine.ext import db
import time

# remember wavelet <-> blip id for communication --> stored in db
class WaveModel(db.Model):
	"""wavelet info and blip response are assiociated and remebered"""
	waveletKey = db.StringProperty(required=True)
	blipId = db.StringProperty(required=True)

def OnParticipantsChanged(properties, context):
	""" do nothing """
	
	
def OnRobotAdded(properties, context):
	root_wavelet = context.GetRootWavelet()
	root_blip = root_wavelet.GetRootBlipId()
	my_blip = root_wavelet.CreateBlip()
	my_blip.GetDocument().SetText("Ready and listening!")
	# if owner is registered store the waveletkey and remember the Blip element + tell that you are ready
	try:
		wave = WaveModel(
			waveletKey = root_wavelet.GetId(),
			blipId =  my_blip.GetId()
			)
		wave.put()
		# we have to put a private annotation because we don't have the blip id yet (TBD)
		# in the next message, we will catch up the annotation again and update the model
		root_blip.GetDocument().AnnotateDocument('sbw-app01Robot',str(wave.key()))
		my_blip.GetDocument().SetText("Document annotated with key:"+str(wave.key()))
	except Exception, e:
		my_blip.GetDocument().SetText("We are in trouble:"+e.message)

def OnDocumentChange(properties, context):
	root_wavelet = context.GetRootWavelet()
	# let's search within the root blip for annotation: sbw-app01Robot
	
def Notify(context):
	root_wavelet = context.GetRootWavelet()
	root_wavelet.CreateBlip().GetDocument().SetText("Hi everybody")

if __name__ == '__main__':
	myRobot = robot.Robot('sbw-app01',
		image_url='http://sbw-app01.appspot.com/assets/avatar.png',
		version='2',
		profile_url='http://sbw-app01.appspot.com/')
	myRobot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, OnParticipantsChanged)
	myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
	myRobot.RegisterHandler(events.DOCUMENT_CHANGED, OnDocumentChange)
	myRobot.Run()
